<template>
  <div id="chat-list-page"
       v-loading="isLoading"
       element-loading-text="拼命加载中"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <div id="chat-box" :style="{height:currHeight+'px'}">
      <div class="chat-title" v-text="currChatSession.id>0?('【'+currChatSession.fromUserName+'】聊天'):'-'"></div>
      <div v-if="currChatSession.id>0" id="content-wapper" class="my-scroller" ref="content-wapper"
           :style="{
      height: currHeight+'px'
    }">
        <div id="content">
          <div class="item">
            <div style="line-height: 40px; height: 40px; color: #276bb2; font-weight: bold; text-decoration: underline; cursor:pointer;"
                 @click="getNewMessageList('before')"
                 v-if="moreMessageNums>pageSize">
              <span v-text="'加载更多....'"></span>
            </div>
          </div>
          <div class="item" v-for="(item,index) in messageList">
            <div class="time" v-if="item.timeInfo">
              <span> {{ item.timeInfo }} </span>
            </div>
            <template v-if="item.fromUserType!=='Shop'">
              <div class="item-content shop">
                <div class="icon">
                  <div class="img" :style="{backgroundImage:'url('+item.fromUserIcon+')'}"></div>
                </div>
                <div class="message" @click="setCurrId(item.id)" :class="{curr:item.id===currId}">
                  <div class="text" v-html="showMessage(item)"></div>
                  <i class="el-icon-error" @click="deleteMessage(index,item)"></i>
<!--                  <div class="time" v-text="item.createdTime.substring(5)"></div>-->
                </div>
                <div class="c"></div>
              </div>
            </template>

            <template v-if="item.fromUserType==='Shop'">
              <div class="item-content me">
                <div class="icon">
                  <div class="img" :style="{backgroundImage:'url('+CurrUser.icon+')'}"></div>
                </div>
                <div class="message"  @click="setCurrId(item.id)" :class="{curr:item.id===currId}">
                  <div class="text" v-html="showMessage(item)"></div>
<!--                  <div class="time" v-text="item.createdTime.substring(5)"></div>-->
                  <i class="el-icon-error" @click="deleteMessage(index,item)"></i>
                </div>
                <div class="c"></div>
              </div>
            </template>
          </div>
        </div>
      </div>

      <div id="bottom-box" v-if="currChatSession && currChatSession.id>0">
        <div class="image-upload-box">
          <el-upload
            name="myUploadFile"
            :action="UploadFileUrl"
            :headers="getHeader()"
            :show-file-list="false"
            accept="image/png, image/jpeg, image/jpg, image/gif, video/mp4, video/quicktime"
            :before-upload="checkUploadFile"
            :on-success="successUpload">
            <i class="el-icon-picture upload-icon"></i>
          </el-upload>

        </div>
        <!--      <div class="icon-box">-->
        <!--        <emotion-box/>-->
        <!--        <i class="iconfont icon-biaoqing"></i>-->
        <!--      </div>-->
        <div class="input-box">
          <el-input :maxlength="500" style="width: 1200px;" @keyup.enter.native="sendTextMessage" size="small" v-model="sendMessageContent" ref="sendMessageContent"></el-input>
        </div>
        <div class="submit-box">
          <el-button type="danger" @click="sendTextMessage" v-if="!sendMessageTextButtonLoading">发送</el-button>
          <el-button type="danger" v-if="sendMessageTextButtonLoading" disabled>发送中</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Viewer from 'viewerjs'

export default {
  name: 'ChatBox',
  data: function () {
    return {
      currId:0,
      isLoading: false,
      sendMessageContent:'',
      messageList: [],
      messageTotal: [],
      myGallery: false,
      myIscroll: false,
      sendMessageTextButtonLoading: false,
      currHeight: 500,
      pageSize:20,
      moreMessageNums:0,
      currChatSession: {
        "id": 0,
        "userId": 74,
        "mainId": 7,
        "userType": "Shop",
        "fromMainId": 22,
        "fromUserId": 22,
        "fromUserType": "Member",
        "fromIcon": "http://image.yangfankj.com/icon/19.png",
        "fromName": "愚笨",
        "lastMessage": "",
        "unReadNums": 0,
        "lastMessageTime": null,
        "fromSessionId": null
      },
    }
  },
  mounted () {
    let $this = this
    setTimeout(function () {
      $this.getUserInfo()
    },600)
    $this.getTableHeight()
    setTimeout(function () {
      if ($this.currChatSession && $this.currChatSession.id>0){
        $this.$refs['sendMessageContent'].focus()
      }
    },1500)

    $this.bus.$on('NewSocketMessage', function (data) {
      // 判断当前消息,是否为当前会话
      if (data.userId === $this.currChatSession.fromUserId) {
        $this.getNewMessageList('after')
      }
      // 其他端发送消息(自动同步)
      if (data.userType==='Shop' && data.message === 'UPDATENEW') {
        $this.getNewMessageList('after')
      }
    })
  },
  destroyed () {
    this.bus.$off('NewSocketMessage')
  },
  methods: {
    setCurrId:function (id) {
      if (this.currId===id){
        this.currId=-1
        this.$forceUpdate()
        return;
      }
      this.currId=id
      this.$forceUpdate()
    },
    // 计算高度
    getTableHeight:function () {
      var height=this.getWinSize().height-190
      this.currHeight=height>500?height:500
    },
    // 设置当前聊天-会话
    setSession:function (session) {
      let $this=this
      $this.messageList=[]
      $this.messageTotal=0
      $this.moreMessageNums=0
      $this.currChatSession=session
      // 获取参数中店铺信息
      $this.getChatSessionDetail(function () {
        // 获取最新消息(10条)
        $this.getNewMessageList('new')
      })
    },
    getUserInfo: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameShop + 'Home/userInfo', {}, function (data) {
        $this.CurrUser.icon = data.icon
        $this.CurrUser.nickname = data.nickname
        $this.CurrUser.sex = data.sex
        $this.$forceUpdate()
      }, function (data) {
        $this.$forceUpdate()
        $this.$message.error(data.message, 'error')
      })
    },
    // 获取聊天会话信息
    getChatSessionDetail: function (callback) {
      var url = 'Home/chatMessageSessionDetail'
      var params = {chatSessionId: this.currChatSession.id}


      let $this = this
      $this.isLoading = true
      $this.MyRequest($this.ApiDoNameShop + url, params, function (data) {
        $this.isLoading = false
        $this.currChatSession = data
        callback()
        $this.$forceUpdate()
      }, function (data) {
        $this.isLoading = false
        $this.$forceUpdate()
        $this.$message.error(data.message)
      })
    },
    /**
     * 拉取消息
     * @param type
     */
    getNewMessageList: function (type) {
      let $this = this
      $this.isLoading = true
      var requestParams = {
        chatSessionId: $this.currChatSession.id,
        sortProp: 'id',
        sortOrder: 'ASC',
        pageSize: this.pageSize
      }
      if (type === 'new') {
        // requestParams.sortOrder="DESC"
        requestParams.sortOrder = 'DESC'
      }
      if (type === 'before' && this.minMessageId) {
        requestParams.sortOrder = 'DESC'
        requestParams.minMessageId = this.minMessageId
      }
      if (type === 'after' && this.maxMessageId) {
        requestParams.maxMessageId = this.maxMessageId
      }
      $this.isLoading = true
      $this.MyRequest($this.ApiDoNameShop + 'Home/chatMessageList', requestParams, function (data) {
        $this.isLoading = false
        $this.moreMessageNums=data.total
        $this.messageTotal=data.total
        $this.isLoading = false
        $this.$forceUpdate()
        if (type === 'new') {
          data.list = data.list.reverse()
        }
        if (type === 'before') {
          data.list = data.list.reverse()
        }
        if (data.list.length === 0) {
          $this.moreMessageNums=0
          return
        }
        $this.setMessageList(data.list, type)
      }, function (data) {
        $this.isLoading = false
        $this.$forceUpdate()
        $this.$message.error(data.message)
      })
    },
    /**
     * 设置消息
     * @param messageList
     * @param type
     */
    setMessageList: function (messageList, type) {
      let $this = this
      switch (type) {
        // 创建新消息
        case 'new':
          $this.messageList = messageList
          break
        // 获取历史
        case 'before':
          $this.messageList = messageList.concat($this.messageList)
          break
        // 获取新的
        case 'after':
          $this.messageList = $this.messageList.concat(messageList)
          break
      }
      // 1.当条数大于20条,才有可能还有未加载的消息
      if ($this.messageList.length >= $this.pageSize) {
        $this.minMessageId = $this.messageList[0].id
      }
      $this.maxMessageId = $this.messageList[$this.messageList.length - 1].id
      $this.$forceUpdate()
      if (type === 'after' || type === 'new') {
        setTimeout(function () {
          $this.scrollerToBottom()
        }, 500)
      }
      if ($this.messageTotal<=$this.messageList.length){
        $this.moreMessageNums=0
        $this.$forceUpdate()
      }
      // 设置图片消息查看
      $this.handlerImageShow()
      $this.checkTime()
    },
    // 显示消息
    showMessage: function (messageItem) {
      let $this=this
      if (messageItem.messageType.id === 'image') {
        if (messageItem.message.indexOf('mp4')>-1){
          return '<video width="200" height="200" controls><source src="'+messageItem.message+'" type="video/mp4"></video>'
        }else{
          return '<img class="image-message" src="' + messageItem.message + '" />'
        }
      } else if (messageItem.messageType.id === 'video') {
        return '<video width="200" height="200" controls><source src="'+messageItem.message+'" type="video/mp4"></video>'
      } else if (messageItem.messageType.id === 'ShopProduct') {
        return '<div class="message-product">' +
          '<div class="message-product-image"><img src="'+messageItem.fileInfo.image+'"></div>' +
          '<div class="message-product-name ovd_s">'+messageItem.fileInfo.shopProductName+'</div>' +
          '<div class="message-product-model ovd_s">型号: '+messageItem.fileInfo.model+'</div>' +
          '<div class="message-product-price"><span>￥'+$this.ToMoney(messageItem.fileInfo.price)+'</span> <button onclick="showProductDetail(\''+messageItem.fileInfo.type+'\','+messageItem.fileInfo.id+')">查看商品详情</button></div></div>'
      } else if (messageItem.messageType.id === 'SupplierProduct') {
        return '<div class="message-product">' +
          '<div class="message-product-image"><img src="'+messageItem.fileInfo.image+'"></div>' +
          '<div class="message-product-name ovd_s">'+messageItem.fileInfo.supplierProductName+'</div>' +
          '<div class="message-product-model ovd_s">型号: '+messageItem.fileInfo.model+'</div>' +
          '<div class="message-product-price"><span>￥'+$this.ToMoney(messageItem.fileInfo.price)+'</span> <button onclick="showProductDetail(\''+messageItem.fileInfo.type+'\','+messageItem.fileInfo.id+')">查看商品详情</button></div></div>'
      }
      else{
        return messageItem.message
      }
    },
    checkUploadFile:function (file) {
      var fileArr=['image/png','image/jpg','image/jpeg','image/gif','video/mp4','video/quicktime']
      if (fileArr.indexOf(file.type)===-1){
        this.$message.error('只允许上传: '+fileArr.join(',')+' 类型文件')
        return false
      }
      return true
    },
    // 上传成功
    successUpload: function (response,file) {
      let $this = this
      if (response.code === 0) {
        $this.sendMessage(response.data, 'image')
      } else {
        $this.$message.error('聊天上传图片失败: ' + response.message)
      }
    },
    // 发送消息
    sendMessage: function (message, messageType) {
      let $this = this
      $this.isLoading = true
      if (messageType === 'text') {
        $this.sendMessageTextButtonLoading = true
      }
      $this.MyRequest($this.ApiDoNameShop + 'Home/chatSendMessage', {
        chatSessionId: $this.currChatSession.id,
        userType: $this.currChatSession.fromUserType,
        platform: 'PC',
        message: message,
        messageType: messageType,
      }, function (data) {
        $this.isLoading = false
        $this.sendMessageTextButtonLoading = false
        $this.$forceUpdate()
        if (messageType === 'text') {
          $this.sendMessageContent = ''
        }
        $this.getNewMessageList('after')
      }, function (data) {
        $this.isLoading = false
        $this.$forceUpdate()
        $this.$message.error(data.message)
      })
    },
    sendTextMessage: function () {
      if (this.sendMessageContent.length<=0){
        return this.$message.error('消息内容不能为空')
      }
      this.sendMessage(this.sendMessageContent, 'text')
    },
    handlerImageShow: function () {
      let $this = this
      if ($this.myGallery) {
        $this.myGallery.destroy()
      }
      setTimeout(function () {
        $this.myGallery = new Viewer(document.getElementById('content-wapper'))
      }, 500)
    },
    scrollerToBottom:function () {
      var dom=this.$refs['content-wapper']
      dom.scrollTop=9999
    },
    checkTime:function () {
      let $this=this
      $this.messageList.forEach(function (value, index) {
        if (index===0){
          console.log('sss')
          $this.$set($this.messageList[index],'timeInfo',value.createdTime.substring(0,16))
          // value.timeInfo=value.createdTime.substring(0,12)
        }else{
          var beforeDate = Date.parse($this.messageList[index-1].createdTime)/1000
          var date = Date.parse(value.createdTime)/1000
          var diff=date-beforeDate
          if (diff>300){
            $this.$set($this.messageList[index],'timeInfo',value.createdTime.substring(0,16))
          }
        }
      })
    },
    deleteMessage: function (index,messageItem) {
      let $this = this
      $this.$confirm('您确认要进行该操作吗?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        $this.isLoading = true
        $this.MyRequest($this.ApiDoNameShop + 'Home/chatSendMessageDelete', {
          id: messageItem.id,
        }, function (data) {
          $this.isLoading = false
          $this.messageList.splice(index,1)
          $this.checkTime()
          $this.$forceUpdate()
        }, function (data) {
          $this.isLoading = false
          $this.$forceUpdate()
          $this.successTip(data.message, 'error')
        })
      }).catch(() => {

      });

    },
  }
}
</script>

<style scoped>

</style>
